package com.cedarhd.finance.log.domain.repository.specification;

import com.cedarhd.finance.log.domain.entity.ErrorLog;
import com.cedarhd.finance.log.dto.ErrorLogDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;

/**
 * @author Evan
 * @date 2018/3/6
 */
public class ErrorLogSpecification {
    public static Specification<ErrorLog> buildFromDTO(ErrorLogDto dto) {
        return (root, query, builder) -> {

            ArrayList<Predicate> list = new ArrayList<>();

            if (StringUtils.isNotBlank(dto.getCode())) {
                list.add(builder.like(root.get("code"), "%" + dto.getCode() + "%"));
            }

            if (dto.getUrgent() != null) {
                list.add(builder.equal(root.get("urgent"),dto.getUrgent()));
            }

            if (StringUtils.isNotBlank(dto.getShowDesc())) {
                list.add(builder.like(root.get("showDesc"),"%" + dto.getShowDesc() + "%" ));
            }

            if (StringUtils.isNotBlank(dto.getSysDesc())) {
                list.add(builder.like(root.get("sysDesc"),"%" + dto.getSysDesc() + "%" ));
            }

            Predicate[] predicates = new Predicate[list.size()];
            predicates = list.toArray(predicates);

            return builder.and(predicates);
        };
    }

}
